import React, { useState, useRef } from 'react'
import SimpleMDE from "react-simplemde-editor"
import { faPlus, faFileImport, faSave, fas } from '@fortawesome/free-solid-svg-icons'
import { v4 as uuidv4 } from 'uuid'
import FileSearch from './components/FileSearch'
import FileList from './components/FileList'
import BottomBtn from './components/BottomBtn'
import TabList from './components/TabList'
import ConfirmModal from './components/Confirm'
import { flattenArr, objToArr } from './utils'
import fileHelper from './utils/file'
import './bootstrap.min.css'
import "easymde/dist/easymde.min.css"
import './App.css'
// const { ipcRenderer } = window.electron
// 引用node模块 
const { join, parse } = window.require('path')
const ele = window.require('@electron/remote')
const Store = window.require('electron-store');
const fileStore = new Store({ name: 'Files Data' })
// fileStore.set('name', 'hello')
// console.log(fileStore.get('name'));
const saveFileToStore = (files) => {
  const fileStoreObj = objToArr(files).reduce((result, file) => {
    const { id, title, createdAt, path } = file
    result[id] = {
      id,
      title,
      createdAt,
      path
    }
    return result
  }, {})
  console.log(fileStoreObj, 'fileStoreObj--');
  fileStore.set('files', fileStoreObj)
}
function App() {
  let nowDeleteId = useRef('')
  const [files, setFiles] = useState(fileStore.get('files') || {})
  const [searchFiles, setSearchFiles] = useState([])
  const [activeFileID, setActiveFileID] = useState('')
  const [openedFileIDs, setOpenedFileIDs] = useState([])
  const [unsavedFileIDs, setUnsavedFileIDs] = useState([])
  const [showConfirm, setShowConfirm] = useState(false)
  const filesArr = objToArr(files)
  const openedFiles = openedFileIDs.map(id => {
    return files[id]
  })
  const activeFile = files[activeFileID]
  const getFiles = searchFiles.length ? searchFiles : filesArr
  // documents 用户文档目录的路径
  // downloads 用户下载目录的路径
  const saveLocation = ele.app.getPath('downloads')
  console.log(saveLocation);
  const onFileClick = async (id) => {
    // 设置当前id
    setActiveFileID(id)
    const currentFile = files[id]
    if (!currentFile.isLoad) {
      try {
        const value = await fileHelper.readFile(currentFile.path)
        const newFile = { ...files[id], body: value, isLoad: true }
        setFiles({ ...files, [id]: newFile })
      } catch (error) {
        console.log('数据读取失败', error);
      }
    }
    // 设置到右边的打开列表中
    if (!openedFileIDs.includes(id)) {
      setOpenedFileIDs([...openedFileIDs, id])
    }
  }
  // 编辑文件标题
  const onSaveFileEdit = async (id, title, isNew) => {
    const oldTitle = files[id].title
    files[id].title = title
    files[id].isNew = false
    const path = join(saveLocation, `${title}.md`)
    files[id].path = path
    if (isNew) {
      // 新建
      try {
        await fileHelper.writeFile(path, files[id].body)
        setFiles({ ...files })
        saveFileToStore(files)
        console.log('新建成功');
      } catch (error) {
        console.log('新建文件失败', error);
      }
    } else {
      // 编辑
      try {
        await fileHelper.renameFile(join(saveLocation, `${oldTitle}.md`), path)
        setFiles({ ...files })
        saveFileToStore(files)
        console.log('编辑成功');
      } catch (error) {
        console.log('编辑文件失败', error);
      }
    }

  }
  // 删除文件
  const onDeleteFile = async () => {
    setShowConfirm(false)
    // ele.dialog.showMessageBox({
    //   title: '提示',
    //   message: '是否要删除文件',
    //   type: 'warning',
    //   buttons: ['取消', '确定'],
    // })

    // return

    const id = nowDeleteId.current
    if (id) {
      if (files[id].isNew) {
        // delete files[id]
        // setFiles({ ...files })
        const { [id]: value, ...afterDelete } = files
        setFiles(afterDelete)
      } else {
        try {
          await fileHelper.deleteFile(files[id].path)
          // delete files[id]
          // setFiles({ ...files })
          // saveFileToStore(files)
          const { [id]: value, ...afterDelete } = files
          setFiles(afterDelete)
          saveFileToStore(afterDelete)
          closeTab(id)
          console.log('文件删除成功');
        } catch (error) {
          console.log('删除文件失败', error);
        }
      }
    }

  }
  // 点击tab
  const tabClick = (id) => {
    // 设置当前id
    setActiveFileID(id)
  }
  // 关闭tab
  const closeTab = (id) => {
    const tabs = openedFileIDs.filter(r => r !== id)
    setOpenedFileIDs(tabs)
    if (tabs.length) {
      setActiveFileID(tabs[0])
    }
    else {
      setActiveFileID('')
    }
  }
  // 监听mad输入
  const onMdChange = (id, value) => {
    // 当前tab在输入，则加入未保存列表
    if (!unsavedFileIDs.includes(id)) {
      setUnsavedFileIDs([...unsavedFileIDs, id])
    }
    files[id].body = value
    setFiles({ ...files })
  }
  // 搜素文件列表
  const fileSearch = (fileTitle) => {
    const newFiles = filesArr.filter(r => r.title.includes(fileTitle))
    setSearchFiles(newFiles)
  }
  // 新建文件
  const createNewFile = (title = '', body = 'hello md') => {
    const id = uuidv4()
    files[id] = {
      id,
      title,
      body,
      createdAt: Date.now(),
      path: '',
      isNew: true
    }
    setFiles({ ...files })
    return files[id]
  }
  // 导入文件
  const exportNewFile = async () => {
    try {
      const { canceled, filePaths } = await ele.dialog.showOpenDialog({
        title: '选择要导入的 MarkDown 文件',
        properties: ['openFile', 'multiSelections'],
        filters: [
          { name: 'MarkDown files', extensions: ['md'] },
        ]
      })
      if (!canceled) {
        // 创建文件 
        if (filePaths && filePaths.length) {
          for (let i = 0; i < filePaths.length; i++) {
            const path = filePaths[i]
            const { base, name } = parse(path)
            const value = await fileHelper.readFile(path)
            const file = createNewFile(name, value)
            await onSaveFileEdit(file.id, name, true)
          }
        }

      }
    } catch (error) {
      console.log('导入文件失败', error);
    }
  }
  // 保存当前在编辑md文件
  const saveCurrentFile = async () => {
    try {
      await fileHelper.writeFile(join(saveLocation, `${activeFile.title}.md`), activeFile.body)
      setUnsavedFileIDs(unsavedFileIDs.filter(id => id !== activeFile.id))
      console.log('文件保存成功');
    } catch (error) {
      console.log('文件保存失败', error);
    }
  }

  return (
    <div className="App container-fluid px-0">
      <ConfirmModal
        show={showConfirm}
        content="是否删除改文件？"
        onClose={() => { setShowConfirm(false) }}
        onOk={() => { onDeleteFile() }}
      />
      <div className="row no-gutters">
        <div className="col-3 left-panel">
          <FileSearch
            title="我的云文档"
            onFileSearch={fileSearch}
          />
          <FileList
            files={getFiles}
            onFileClick={(id) => { onFileClick(id) }}
            onSaveEdit={(id, newValue, isNew) => { onSaveFileEdit(id, newValue, isNew) }}
            onFileDelete={(id, isNew) => {
              nowDeleteId.current = id;
              if (!isNew) {
                setShowConfirm(true)
              } else {
                onDeleteFile()
              }

            }}
          />
          <div className="row no-gutters">
            <div className="col-6 d-grid gap-1 mx-auto btn-box">
              <BottomBtn
                text="新建"
                icon={faPlus}
                colorClass="btn-primary"
                onBtnClick={createNewFile}
              />
            </div>
            <div className="col-6 d-grid gap-1 mx-auto btn-box">
              <BottomBtn
                text="导入"
                icon={faFileImport}
                colorClass="btn-success"
                onBtnClick={exportNewFile}
              />
            </div>
          </div>
        </div>
        <div className="col-9 right-panel">
          {!activeFile && <div className="start-page">选择或创建新的 MarketDown文件</div>}
          {
            activeFile &&
            <>
              <TabList
                files={openedFiles}
                activeId={activeFileID}
                unsaveIds={unsavedFileIDs}
                onTabClick={tabClick}
                onCloseTab={closeTab}
              />
              <SimpleMDE
                key={activeFile && activeFile.id}
                value={activeFile && activeFile.body}
                onChange={(value) => { onMdChange(activeFile.id, value) }}
                options={{
                  minHeight: '515px'
                }}
              />
              <BottomBtn
                text="保存"
                icon={faSave}
                colorClass="btn-primary"
                onBtnClick={saveCurrentFile}
              />
            </>
          }
        </div>
      </div>
    </div>
  );
}

export default App;
